package com.hengtiansoft.lfy.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.chart.applib.utils.HXPreferenceUtils;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.db.been.OneMobileDB;
import com.hengtiansoft.lfy.utils.AudioRecordUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.utils.JsonParser;
import com.hengtiansoft.lfy.utils.Kdxf_TTSPlayer;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.ztspeech.constant.ZTConstant;
import com.ztspeech.translator.ZTTranslator;
import com.ztspeech.translator.interf.ZTTranslatorListener;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName: VoiceDialogActivity
 * @Description: 语音识别dialog
 * 
 */
public class Kdxf_CustomAudio_VoiceDialogActivity extends FragmentActivity
        implements OnClickListener {
    private final static String TAG = Kdxf_CustomAudio_VoiceDialogActivity.class.getSimpleName();
    private TextView mTvText;
    private LinearLayout mRlCancel;//取消
    private Drawable[] micImages;
   private String transferType;
//    private ProgressDialog mPd;
    private Long date;
    public static final String Basic_PATH = Environment
            .getExternalStorageDirectory().getAbsolutePath() + File.separator
            + "longfanyi/voice/";
    public static final String Basic_PATH_data = "/data/data/com.hengtiansoft.lfy/longfanyi/voice/";
  //  String url;
    /*--------------科大讯飞--------------------*/
    // 语音听写对象
    private SpeechRecognizer mIat;
    public String kdxf_transferType="zh_cn";
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    //是否取消语音识别
    private boolean iscanelVoice=false;

    private LinearLayout lv_top;
    private Button btn_chinese;
    private Button btn_english;
    private ImageView[] imageViews;
    private TextView tv_text_original,tv_text_translate;
    private String direction="left";
    // 数据库的存储
    private RuntimeExceptionDao<OneMobileDB, Integer> mOneMobileDBDao = null;
    private boolean isTwoSpeek=false;
    private String other_original="",other_translate="";
    private boolean isStop=false;
    private int index = 6;

    private AudioRecordUtils audioRecordUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_voice);//关闭扬声器
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高
        WindowManager.LayoutParams p = getWindow().getAttributes();
       // p.height = (int) (d.getHeight() * 0.5); // 高度设置为屏幕的0.3
        p.width = (int) (d.getWidth() * 0.7); // 宽度设置为屏幕的0.7
        getWindow().setAttributes(p);
       // CloseSpeaker(); //
        initView();
        setListener();
        this.setFinishOnTouchOutside(false);

    }

    private void initView() {
        // 动画资源文件,用于录制语音时
        micImages = new Drawable[] {
                getResources().getDrawable(R.drawable.sound1),
                getResources().getDrawable(R.drawable.sound2),
                getResources().getDrawable(R.drawable.sound3),
                getResources().getDrawable(R.drawable.sound4),
                getResources().getDrawable(R.drawable.sound5),
                getResources().getDrawable(R.drawable.sound5)}; //16
        mRlCancel = (LinearLayout) findViewById(
                R.id.rl_translate_recording_voice_cancel); //取消
        imageViews=new ImageView[index];
        imageViews[0]= (ImageView) findViewById(R.id.translate_recording_voice_img1);
        imageViews[1]= (ImageView) findViewById(R.id.translate_recording_voice_img2);
        imageViews[2]= (ImageView) findViewById(R.id.translate_recording_voice_img3);
        imageViews[3]= (ImageView) findViewById(R.id.translate_recording_voice_img4);
        imageViews[4]= (ImageView) findViewById(R.id.translate_recording_voice_img5);
        imageViews[5]= (ImageView) findViewById(R.id.translate_recording_voice_img6);
//        mPd = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
//        mPd.setCanceledOnTouchOutside(false);
//        mPd.setMessage(getString(R.string.is_translating));
        tv_text_original = (TextView) findViewById(R.id.tv_text_original); //原文
        tv_text_translate= (TextView) findViewById(R.id.tv_text_translate);//翻译后文字
        transferType = getIntent().getStringExtra("transferType"); //翻译类型
        lv_top= (LinearLayout) findViewById(R.id.lv_top);
        isTwoSpeek=false;
        if("ench".equals(transferType)){
            //英文到中文
            tv_text_original.setText(getString(R.string.pleaseSpeekEnglish));
            lv_top.setVisibility(View.GONE);
            kdxf_transferType="en_us";
            direction="right";
        }else if("chen".equals(transferType)){
            //中文到英文
            tv_text_original.setText(getString(R.string.pleaseSpeekChine));
            lv_top.setVisibility(View.GONE);
            kdxf_transferType="zh_cn";
            direction="left";
        }else{
            lv_top.setVisibility(View.VISIBLE);
            btn_chinese= (Button) findViewById(R.id.btn_chinese);
            btn_english= (Button) findViewById(R.id.btn_english);
            //btn_english.setOnClickListener(this);
            //btn_chinese.setOnClickListener(this);
            tv_text_original.setText(getString(R.string.pleaseSpeekChine));
            kdxf_transferType="zh_cn";
            transferType="chen";
            isTwoSpeek=true;
        }
        date = getIntent().getLongExtra("date", System.currentTimeMillis());
        Log.i(TAG, System.currentTimeMillis() + "");
        String username="";
        if(Config.isUserLogined()){
            username=Config.getUserName();
            if(TextUtils.isEmpty(username)){
                username="root";
            }
        }else{
            username="root";
        }
        String path = Basic_PATH_data
                + username+ "/"; //存贮目录//LFYApplication.getInstance().getUserName()
        File destDir = new File(path);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
       // url = path + System.currentTimeMillis() + ".wav"; //文件路径
        audioRecordUtils = new AudioRecordUtils();
        audioRecordUtils.setMFRec(true);//开启男女声识别
        startVoice();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(isStop==false) {
            mRlCancel.performClick();
        }
    }

    private void setListener() {
        mRlCancel.setOnClickListener(this);
    }
    public String result="";
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.rl_translate_recording_voice_cancel:
                isStop = true;
                stopVoice();
//            mPd.dismiss();
                tv_text_translate.setText("");
                if (isTwoSpeek == false) {
                    if (!TextUtils.isEmpty(other_translate))
                        setDataToOneMobileDB(other_original, other_translate, direction);
                }
                setResult(RESULT_OK);
                clear();
                finish();
            break;
//            case R.id.btn_chinese:
//
//                break;
//            case R.id.btn_english:
//
//                break;
        default:
            break;
        }
    }
    private int number=0;
    public void doshowAnim(int voice,boolean isNo){
        if(number==index){
            number=0;
        }
        if(isNo){
            imageViews[number].setImageDrawable(null);
        }else {
            imageViews[number].setImageDrawable(micImages[voice]);
        }
        number++;
    }
    /**
     * 开始录音
     */
    public void startVoice() {
        //-------------------------------------科大讯飞
        //TTSPlayer.getInstense().stop();//语音播放停止
        Kdxf_TTSPlayer.getInstense().stop();
        // 初始化识别无UI识别对象
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
        setParam();
        mIat.startListening(recognizerListener);
        audioRecordUtils.startRecord(callBack);
    }
    //监听器
    private RecognizerListener recognizerListener=new RecognizerListener() {
        //volume音量值0~30， data音频数据
        @Override
        public void onVolumeChanged(int i, byte[] bytes) {
            if(i<=1){
                doshowAnim(0,true);
            }else{
                doshowAnim(i/6,false);
            }
        }
        //开始录音
        @Override
        public void onBeginOfSpeech() {
            Log.i("supeng","onBeginOfSpeech");
        }
        //结束录音
        @Override
        public void onEndOfSpeech() {
            Log.i("supeng","onEndOfSpeech");
            audioRecordUtils.stopRecord();
            if(iscanelVoice){
                Intent intent = new Intent();
                intent.putExtra("result", Constants.ZR_STOP_NULL);
                setResult(RESULT_OK, intent);
                finish();
                return;
            }
        }
        //一般情况下会通过onResults接口多次返回结果，完整的识别内容是多次结果的累加；
        //关于解析Json的代码可参见Demo中JsonParser类；
        //isLast等于true时会话结束。
        @Override
        public void onResult(RecognizerResult recognizerResult, boolean isLast) {
            result=result+getStringResult(recognizerResult);
            if (isLast) {
                if(iscanelVoice){
                    Intent intent = new Intent();
                    intent.putExtra("result", Constants.ZR_STOP_NULL);
                    setResult(RESULT_OK, intent);
                    finish();
                    return;
                }
               // String recoResult = result; //翻译后的文字
             //   String Basic_PATH = url;//压缩过后的原始音频
              //  Log.i("supeng","url="+url+",res="+result);
                String[] a = Basic_PATH.split("/");
                int i = a.length;
                int j = i - 1;
                translator(result);
              /*  Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("url", Basic_PATH);
                intent.putExtra("fileName", a[j]);//文件名
                Log.i(TAG, "Basic_PATH:" + Basic_PATH + "fileName" + a[j]);
                setResult(RESULT_OK, intent);
                finish();*/
            }
        }
        //会话发生错误回调接口
        // Tips：
        // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
        // 如果使用本地功能（语记）需要提示用户开启语记的录音权限。
        @Override
        public void onError(SpeechError speechError) {
            Log.i("supeng","error="+speechError.getErrorCode());
            if(iscanelVoice){
               /* Intent intent = new Intent();
                intent.putExtra("result", Constants.ZR_STOP_NULL);
                setResult(RESULT_OK, intent);
                finish();*/
                translator(Constants.ZR_STOP_NULL);
                return;
            }
            if("10118".equals(speechError.getErrorCode()+"")){
                //Toast.makeText(Dialog_Voice_Activity.this, "您没有说话", Toast.LENGTH_LONG).show();
               // String res= "No_RESULT";
                translator(Constants.No_RESULT);
                /*Intent intent = new Intent();
                intent.putExtra("result", Constants.No_RESULT);
                setResult(RESULT_OK, intent);
                finish();*/
            }else{
                translator(Constants.ZR_ERROR);
                /*Intent intent = new Intent();
                intent.putExtra("result", Constants.ZR_ERROR);
                setResult(RESULT_OK, intent);
                finish();*/
               // Toast.makeText(Dialog_Voice_Activity.this,"异常"+speechError.getPlainDescription(true),Toast.LENGTH_LONG).show();
            }
            /*finish();*/
        }
        //扩展用接口
        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    };
    private void circleSpeak(){
        result="";
        textTask="";
        if("ench".equals(transferType)){ //反过来 中文
            direction="left";
            kdxf_transferType="zh_cn";
           // tv_text_original.setText(getString(R.string.pleaseSpeekChine));
            tv_text_translate.setText("");

            transferType="chen";
            delayStartVoice();
        }else {
            direction = "right";
            kdxf_transferType = "en_us";
            tv_text_translate.setText("");
          //  tv_text_original.setText(getString(R.string.pleaseSpeekEnglish));
            transferType="ench";
            delayStartVoice();

        }
    }
    private String  textTask=""; //原文
    public void translator(String res){
        if(isStop){
            return;
        }
      //  String res = data.getStringExtra("result");
        if (res != null && !res.equals("")) {
            if (res.equals(Constants.No_RESULT)) {
//                Toast.makeText(this, getString(R.string.say_again),
//                        Toast.LENGTH_SHORT).show();
//                if(isTwoSpeek){
//                    circleSpeak();
//                }else{
                    tv_text_original.setText(getString(R.string.say_again));
                    delayStartVoice();
        //        }
            } else if (res.equals(Constants.ZR_ERROR)) {
                Toast.makeText(this, getString(R.string.recognition_error), Toast.LENGTH_SHORT)
                        .show();
                if(isTwoSpeek){
                    circleSpeak();
                }else{
                    mRlCancel.performClick();
//                    delayStartVoice();
                }
            } else if (res.equals(Constants.ZR_STOP_NULL)) {
                if(isTwoSpeek){
                    circleSpeak();
                }else{
//                    delayStartVoice();
                    mRlCancel.performClick();
                }
                return;
            } else {
//                mPd.dismiss();
//                mPd.show();
                tv_text_translate.setText(getString(R.string.is_translating));
                textTask=res;
                //tv_text_original.setText(res);
                if("chen".equals(transferType)){
                    ZTTranslator.getTranslatorInstance().setLanguage(ZTConstant.HTTP_LANGUAGE_CHEN);
                }else{
                    ZTTranslator.getTranslatorInstance().setLanguage(ZTConstant.HTTP_LANGUAGE_ENCH);
                }
                ZTTranslator.getTranslatorInstance().translate(mTranLisenter,res);
            }
        } else {
            Toast.makeText(this, getString(R.string.recognition_error), Toast.LENGTH_SHORT).show();
            if(isTwoSpeek){
                circleSpeak();
            }
//            mRlCancel.performClick();
        }
    }
    /**
     * 紫冬翻译回调接口
     */
    private ZTTranslatorListener mTranLisenter = new ZTTranslatorListener() {
        @Override
        public void onResult(final String text) {
            if(isStop){
                return;
            }
//            mPd.dismiss();
            tv_text_translate.setText("");
            other_original=other_original+textTask;
            other_translate=other_translate+" "+text;
            if (isTwoSpeek) {
                tv_text_original.setText(textTask);
                tv_text_translate.setText(text);
            }else{
                tv_text_original.setText(other_original);
                tv_text_translate.setText(other_translate);
            }
            if (LFYApplication.getInstance().getSettingAutoPlayer()) {
                //TTSPlayer.getInstense().TTSPlay(result);
                Kdxf_TTSPlayer.getInstense().TTSPlay(text,transferType,"",getSpeaker());
                Kdxf_TTSPlayer.getInstense().setStopListener(new Kdxf_TTSPlayer.StopListener() {
                    @Override
                    public void stop() {
                       // if(isStop==false) {
                            if (isTwoSpeek) {
                                setDataToOneMobileDB(textTask, text, direction);
                                circleSpeak();
                            } else {
                                if(isStop==false) {
                                    result = "";
                                    textTask = "";
//                            delayStartVoice();
                                    mRlCancel.performClick();
                                }
                            }
                      //  }
                    }
                });
            }else {
              //  if(isStop==false) {
                    if (isTwoSpeek) {
                        setDataToOneMobileDB(textTask, text, direction);
                        circleSpeak();
                    } else {
                        if(isStop==false) {
                            result = "";
                            textTask = "";
//                    delayStartVoice();
                            mRlCancel.performClick();
                        }
                    }
              //  }
            }
        }

        @Override
        public void onError(int i) {
//            if(mPd != null && mPd.isShowing()){
//                mPd.dismiss();
//            }
            tv_text_translate.setText("");
            Toast.makeText(Kdxf_CustomAudio_VoiceDialogActivity.this, "翻译失败,请检查网络！", Toast.LENGTH_SHORT)
                    .show();
            Log.d(TAG, "翻译错误,错误码:" + i);
            mRlCancel.performClick();
        }
    };
    private void delayStartVoice(){
        if(isStop){
            return;
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(isStop){
                    return;
                }
                if(isTwoSpeek==false){
                    if("ench".equals(transferType)){
                        tv_text_original.setText(getString(R.string.pleaseSpeekEnglish));
                    }else {
                        tv_text_original.setText(getString(R.string.pleaseSpeekChine));
                    }
                }else{
                    if("ench".equals(transferType)){
                        btn_english.setText("Chinese");
                        btn_chinese.setText("English");
                        tv_text_original.setText(getString(R.string.pleaseSpeekEnglish));
                    }else {
                        btn_chinese.setText(getString(R.string.chinese));
                        btn_english.setText(getString(R.string.english));
                        tv_text_original.setText(getString(R.string.pleaseSpeekChine));
                    }
                }
                startVoice();
            }
        },2000);
    }
    private String getStringResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());
        return text;

    }
    private static int currVolume = 0;

   
    public void closeSpeaker() {

        try {
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            //获取当前通话音量
            currVolume =audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
            if(audioManager != null) {
                if(audioManager.isSpeakerphoneOn()) {
                    audioManager.setSpeakerphoneOn(false);
                    audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,currVolume,
                            AudioManager.STREAM_VOICE_CALL);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //Toast.makeText(context,扬声器已经关闭",Toast.LENGTH_SHORT).show();
    }
    /**
     * 添加至本地数据库
     *
     * @param text
     * @param translation
     * @param direction
     */
    public void setDataToOneMobileDB(String text, String translation,
                                     String direction) {
        String username;
        if(Config.isUserLogined()) {
            username= Config.getUserName();
        }else {
            username = "robot";
        }
        //
//        if (DemoHXSDKHelper.getInstance().isLogined()) {
//            username = LfyApplication.getInstance().getUserName();
//        } else {
     //   }
        OneMobileDB oneMobileDB = new OneMobileDB();
        oneMobileDB.setUsername(username);
        oneMobileDB.setText(text);
        oneMobileDB.setTranslation(translation);
        oneMobileDB.setDirection(direction);
        mOneMobileDBDao = LFYApplication.getHelper(this).getOneMobileDao();
        if (null != mOneMobileDBDao) {
            mOneMobileDBDao.create(oneMobileDB);
        }
//        mPd.dismiss();
    }
    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            Log.d(TAG, "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Log.d(TAG, "初始化失败");
            }
        }
    };
    private void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
        //本地自行录音
        mIat.setParameter(SpeechConstant.AUDIO_SOURCE,"-1");

        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, kdxf_transferType);
        if(kdxf_transferType.equals("zh_cn")) {
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        }


        if(isTwoSpeek){
            mIat.setParameter(SpeechConstant.VAD_EOS, "2000");
            mIat.setParameter(SpeechConstant.VAD_BOS, "5000");
        }else {
            // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
            mIat.setParameter(SpeechConstant.VAD_EOS, "2000");
            // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
            mIat.setParameter(SpeechConstant.VAD_BOS, "5000");
        }
        //设置最大超时
        mIat.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, "60000");
        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "1");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "pcm");
//        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,url);
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/long_iat.pcm");
    }
    /**
     * 停止
     */
    public void stopVoice() {
        //---------------------------------
        audioRecordUtils.stopRecord();
        mIat.cancel();//取消识别
        mIat.stopListening();//停止识别
        Kdxf_TTSPlayer.getInstense().setStopListener(null);
    }


    /**
     * 停止不返回数据
     */
    public void stopVoiceNoResult() {
        //------------------------------
        iscanelVoice=true;
        audioRecordUtils.stopRecord();
        mIat.cancel();//取消识别
        Intent intent = new Intent();
        intent.putExtra("result", Constants.ZR_STOP_NULL);
        setResult(RESULT_OK, intent);
        finish();

    }

    /**
     * 清理可能存在的任务
     */
    private void clear() {
        Kdxf_TTSPlayer.getInstense().stopTTs();
        Kdxf_TTSPlayer.getInstense().stop();
        Kdxf_TTSPlayer.getInstense().setExternalTtsListener(null);
        audioRecordUtils.stopRecord();
        mIat.cancel();//取消识别
    }

    /**
     * 录音器回调
     */
    private AudioRecordUtils.AudioRecordCallBack callBack = new AudioRecordUtils.AudioRecordCallBack() {
        @Override
        public void inputWaveData(byte[] data, int start, int count) {
            mIat.writeAudio(data,start,count);
        }

        @Override
        public void error(String err) {

        }

        @Override
        public void speakGender(String gender) {
            Log.d("tag","sex = "+gender);
            if(!"-1".equals(gender)){
                if("chen".equals(transferType)){
                    speakerCTE = gender;
                }else{
                    speakerETC = gender;
                }
            }
        }
    };
    //英-中说话人性别
    private String speakerETC = LFYApplication.getInstance().getSettingSexChoose();
    //中-英说话人性别
    private String speakerCTE = LFYApplication.getInstance().getSettingSexChoose();

    /**
     * 获取说话人
     */
    private String getSpeaker(){
        String voicer = "";
        if (transferType.equals("chen")) {
            if ("f".equals(speakerCTE)) {//女
                voicer = "catherine";
            } else {
                voicer = "henry";
            }
        } else {
            if ("f".equals(speakerETC)) {//女
                voicer = "xiaoyan";
            } else {
                voicer = "xiaoyu";
            }

        }
        return voicer;
    }
}
